\name{codedata}
\alias{codedata}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
Code raw data according to a data dictionary.
}
\description{
Reads data and a data dictionary, perhaps imported from spreadsheets, and outputs a labelled and coded \code{data.frame}.
}
\usage{
codedata(data, tblname, dct = datadic)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
  \item{data}{
a data abject
}
  \item{tblname}{
the name of the data object as defined in the data dictionary
}
  \item{dct}{
a data dictionary data frame with a columns FLDNAME, TBLNAME, CRFNAME, TEXT, TYPE, UNITS, CODE, and NOTES.
}
}
\details{
%%  ~~ If necessary, more details than the description above ~~
}
\value{
%%  ~Describe the value returned
%%  If it is a LIST, use
%%  \item{comp1 }{Description of 'comp1'}
%%  \item{comp2 }{Description of 'comp2'}
%% ...
}
\references{
%% ~put references to the literature/web site here ~
}
\author{
%%  ~~who you are~~
}
\note{
%%  ~~further notes~~
}

%% ~Make other sections like Warning with \section{Warning }{....} ~

\seealso{
%% ~~objects to See Also as \code{\link{help}}, ~~~
}
\examples{
##---- Should be DIRECTLY executable !! ----
##-- ==>  Define data, use random,
##--	or do  help(data=index)  for the standard data sets.

## The function is currently defined as
function(dd, tblname, dct=datadic, dateformat="\%m/\%d/\%Y")){
    require(Hmisc)
    dct <- dct[dct$TBLNAME==toupper(tblname),]
    dct$CODE <- as.character(dct$CODE)
    fldnames = intersect(as.character(colnames(dd)), dct[,"FLDNAME"])
    fldnames = fldnames[!fldnames\%in\%c("ID","RID","PTID","PT_ID","SITE_ID")]
    for(fldname in fldnames){
        code = dct[dct$FLDNAME==toupper(fldname),"CODE"]
        type = dct[dct$FLDNAME==toupper(fldname),"TYPE"]
        if(!is.na(code)&grepl("=", code)){
          code = unlist(strsplit(as.character(code),";"))
          code = lapply(code,strsplit,"=")
          levels = gsub(" ", "", unlist(lapply(code,function(x) x[[1]][1])))
          labels = unlist(lapply(code,function(x) x[[1]][2]))
          dd[,fldname]=factor(as.character(dd[,fldname]),levels=levels,labels=labels)
        }else if( (!is.na(type)&type=="D") ){
          dd[,fldname] = as.character(dd[,fldname])
          # replace missing day with 15th
          dd[,fldname] <- gsub("/--/", "/15/", dd[,fldname])        
          # replace missing month with July
          dd[,fldname] <- gsub("--/", "07/", dd[,fldname])
          dd[,fldname] <- as.Date(dd[,fldname],  format=dateformat)
        }
        labels <- as.character(dct[dct$FLDNAME==toupper(fldname),c("TEXT","UNIT")])
        if(!is.na(labels[1])&labels[1]!="")
        label(dd[,fldname]) <- labels[1]
        if(!is.na(labels[2])&labels[2]!="")
        units(dd[,fldname]) <- labels[2]
    }
    dd
  }
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ ~kwd1 }
\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
